package tedu.boot31.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tedu.boot31.entity.Product;
import tedu.boot31.mapper.ProductMapper;

import java.util.List;

//此注解相当于在每一个方法上添加一个@ResponseBody的注解
@RestController
public class ProductController {

    @Autowired
    ProductMapper mapper;

    @RequestMapping("/insert")
    public String insert(Product product){
        System.out.println("product = " + product);
        mapper.insert(product);
        return "添加成功!<a href='/'>返回首页</a>";
    }

    @RequestMapping("select")
    public String select(){
        List<Product> productList = mapper.selectAllProduct();
        String html = "<table border='1'>";
        html+="<caption>商品列表</caption>";
        html+="<tr><th>编号</th><th>商品名</th><th>价格</th><th>销量</th><th>操作</th></tr>";
        for (Product product : productList) {
            html+="<tr>";
            html+="<td>"+product.getId()+"</td>";
            html+="<td>"+product.getTitle()+"</td>";
            html+="<td>"+product.getPrice()+"</td>";
            html+="<td>"+product.getSaleCount()+"</td>";
            html+="<td><a href='/delete?id="+product.getId()+"'>删除</a></td>";
            html+="</tr>";
        }
//        return productList.toString();
        return html;
    }

    @RequestMapping("/update")
    public String update(Product product){
        System.out.println("product = " + product);
        mapper.updateById(product);
        return "修改成功!<a href='/'>返回首页</a>";
    }

    @RequestMapping("/delete")
    public String delete(Integer id){
        System.out.println("id = " + id);
        mapper.deleteById(id);
        return "删除成功!<a href='/select'>返回列表页面</a>";
    }
}
